package com.irdstudio.apicenter.gateway.web.controller;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

import com.irdstudio.apicenter.gateway.comm.MaccsPacket;
import com.irdstudio.apicenter.gateway.core.jdbc.MaccsBaseDAO;
import com.irdstudio.apicenter.gateway.util.ServletUtil;
import com.irdstudio.apicenter.gateway.util.date.CurrentDateUtil;
import com.irdstudio.apicenter.gateway.util.pub.KeyUtil;
import com.irdstudio.apicenter.gateway.util.spring.BeanUtils;
import com.irdstudio.apicenter.gateway.web.MaccsControllerBus;
import com.irdstudio.apicenter.gateway.web.MaccsEntryServlet;
import com.irdstudio.apicenter.gateway.web.MaccsException;
import com.irdstudio.apicenter.gateway.web.MaccsTradeDefineVo;
import com.irdstudio.apicenter.gateway.web.view.JsonView;
import com.irdstudio.apicenter.gateway.web.view.View;

/**
 * 单点登录交易-获取交易令牌(调用后续的交易可设置需要检查令牌)
 * 
 * @author guangming.li
 * @version 1.0
 * @date 2016-01-12
 */
@Controller
public class AppAccessToken implements IController {
	// 查询是否存在该设备
	private static final String queryAppDeviceRegisterSql = "select * from APP_DEVICE_REGISTER where app_id=? and device_id=?";
	// 新增设备信息
	private static final String insertAppDeviceRegisterSql = "insert into APP_DEVICE_REGISTER values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
	// 更新设备的last_token_id
	private static final String updateAppDeviceRegisterSql = "update app_device_register set last_token_id=?,province_name=? where app_id=? and device_id=?";
	// 查询用户是否已存在（last_token_id为空）
	private static final String queryByUserSql = "select * from APP_DEVICE_REGISTER where app_id=? and app_userid=? and last_token_id is null";
	// 更新设备信息
	private static final String updateDeviceSql = "update app_device_register set last_token_id=? ,token_id=?,app_userid=?,mobile_phone=?,address=?,token_time=?, province_name = ?where app_id=?and device_id=?";
	/* 文本日志输出 */
	private static final Logger logger = LoggerFactory.getLogger(AppAccessToken.class);

	@Override
	public View execute(MaccsTradeDefineVo tradeDefine, MaccsPacket inPacket, HttpServletRequest request,
			HttpServletResponse response) throws MaccsException {

		// 1.产生新的会话令牌
		String tokenId = KeyUtil.createUniqueKey();
		// 2.接收传入的参数并更新到APP_DEVICE_REGISTER表中

		// 获取实际交易码，移动应用标识
		String appId = inPacket.getValue("appId");
		String SignonTradeCode = inPacket.getValue("Signon_trade_code");// 100037

		// 获取省份信息,
		String province = inPacket.getValue("province_name");
		// 获取该标识下的控制总线
		MaccsEntryServlet maccsEntryServlet = new MaccsEntryServlet();
		MaccsControllerBus ctrlBus = maccsEntryServlet.getMaccsControllerBus(appId);
		// 获取自定义私有交易
		MaccsTradeDefineVo newTradeDefine = ctrlBus.getMaccsTradeDefineVo(SignonTradeCode);

		// 3.根据传入的实际登录交易ID去读取交易信息并交给转发交易控制器执行
		TradeForward tradeForward = new TradeForward();
		View view = tradeForward.execute(newTradeDefine, inPacket, request, response);
		// 获取返回的数据
		Map<String, Object> viewData = view.getMapData();
		// 判断是否成功，成功则接收传入的参数并更新到APP_DEVICE_REGISTER表中并组装数据返回，失败则处理，直接返回错误信息
		MaccsBaseDAO jdbcDao = BeanUtils.getBean(MaccsBaseDAO.class);
		if ("0".equals(viewData.get("ec"))) {
			// 获取需要更新到APP_DEVICE_REGISTER的参数
			viewData.put("tokenId", tokenId);
			String address = inPacket.getValue("Address");
			String province_name = getProviceName(province);
			String client_ip = ServletUtil.getRealClientIP(request);
			String token_time = CurrentDateUtil.getTodayDateEx2();
			String secret_key = "";
			String last_token_id = "";
			String device_id = inPacket.getValue("Device_id");
			String app_userid = (String) viewData.get("userno");
			String device_type = inPacket.getValue("Device_type");
			String is_allow = "";
			String mobile_phone = (String) viewData.get("indivmobile");
			String push_device_id = "";
			String device_model = inPacket.getValue("Device_model");
			// 查看该设备
			List<Map<String, Object>> appDeviceRegisterList = jdbcDao.findMapList(queryAppDeviceRegisterSql,
					new Object[] { appId, device_id });
			// 查看该用户
			List<Map<String, Object>> userList = jdbcDao.findMapList(queryByUserSql,
					new Object[] { appId, app_userid });

			if (appDeviceRegisterList.size() == 0 || appDeviceRegisterList == null) {
				// 设备不存在
				if (userList.size() != 0) {
					// 用户存在，获得该用户对应的设备信息，并更新last_token_id为当前token_id,在新增一条记录
					String oldDevice_id = userList.get(0).get("device_id").toString();
					jdbcDao.update(updateAppDeviceRegisterSql,
							new Object[] { tokenId, province_name, appId, oldDevice_id });
				}

				jdbcDao.insert(insertAppDeviceRegisterSql,
						new Object[] { device_id, push_device_id, device_model, device_type, appId, app_userid,
								mobile_phone, is_allow, tokenId, client_ip, address, token_time, secret_key,
								last_token_id, province_name });
			} else {
				// 设备存在，也要判断该用户是否在其他设备登录过
				if (userList.size() != 0) {
					// 用户存在，获得该用户对应的设备信息，并更新last_token_id为当前token_id,在新增一条记录
					String oldDevice_id = userList.get(0).get("device_id").toString();
					jdbcDao.update(updateAppDeviceRegisterSql,
							new Object[] { tokenId, province_name, appId, oldDevice_id });
				}
				// 更新设备信息
				jdbcDao.update(updateDeviceSql, new Object[] { "", tokenId, app_userid, mobile_phone, address,
						token_time, province_name, appId, device_id });
			}
		} else {
			// 登录失败不做处理返回接口错误信息与数据
		}
		MaccsPacket outPacket = new MaccsPacket(viewData);

		return new JsonView(request, response, outPacket);
	}

	/**
	 * 截取省份前面
	 * 
	 * @param province
	 * @return
	 */
	public String getProviceName(String province) {
		// 先判断传入的值是否有效
		if ("".equals(province) || "undefined".equals(province) || "null".equals(province)) {
			return "";
		}
		// 如果是省，截取省前面的值，如果是其他，得根据情况而定
		if (province.contains("省")) {
			// 返回省前面的数值
			return province.substring(0, province.indexOf("省"));
		} else if (province.contains("市")) {
			// 返回市前面的数值
			return province.substring(0, province.indexOf("市"));
		} else {
			// 根据不同情况而定
			if (province.contains("内蒙古")) {
				return province.substring(0, 3);
			} else {
				return province.substring(0, 2);
			}

		}
	}

	public static void main(String[] args) {
		AppAccessToken app = new AppAccessToken();
		System.out.println(app.getProviceName("山西省"));
	}
}
